package com.kaibes.im.view.fragment;

import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;

import com.kaibes.im.R;
import com.kaibes.im.model.SocketWorker;
import com.kaibes.im.model.hanlder.BaseHandler;
import com.kaibes.im.utils.StaticValuesUtil;
import com.kaibes.im.view.CleanableEditeText;
import com.kaibes.im.view.CleanableEditeText.Callback;
import com.kaibes.im.view.RoundImageView;

public class LoginFragment extends KaibesFragment implements OnClickListener {

    public static final int REFRESH_PHOTO = 0X1;
    public static final int REFRESH_USERNAME_PASSWORD_DEFAULT = 0X2;

    private Editor editor;
    private String username = "";
    private String password = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {

	setHandler(new BaseHandler<LoginFragment>(this) {
	    @Override
	    public void handleMessage(Message msg) {
		switch (msg.what) {
		case REFRESH_PHOTO: {
		    getData().setData(getData().username, getData().password);
		    String photoName = getData().getKaibesApplication()
			    .getUserPreferences()
			    .getString(getData().username, "");
		    getData().changePhoto(photoName);
		}
		    break;

		case REFRESH_USERNAME_PASSWORD_DEFAULT: {
		    getData().setUsernameAndPassword(getData().username,
			    getData().password);
		    ((RoundImageView) getView().findViewById(R.id.ivPhotoLogin))
			    .setImageResource(R.drawable.photo_default);
		}
		    break;

		default:
		    break;
		}

	    }
	});
	super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
	    Bundle savedInstanceState) {
	View rootView = inflater.inflate(R.layout.fragment_login, container,
		false);
	rootView.findViewById(R.id.btnLogin).setOnClickListener(this);
	rootView.findViewById(R.id.btnRegister).setOnClickListener(this);
	return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
	setData(getKaibesApplication().getAccountPreferences().getString(
		StaticValuesUtil.USERNAME, ""),
		getKaibesApplication().getAccountPreferences().getString(
			StaticValuesUtil.PASSWORD, ""));
	getView().findViewById(R.id.btnLogin).setOnClickListener(this);
	getView().findViewById(R.id.btnRegister).setOnClickListener(this);
	super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onClick(View v) {
	switch (v.getId()) {
	case R.id.btnLogin: {

	    getKaibesActivity().getProgressDialogData().reset()
		    .setTitle(getString(R.string.login))
		    .setMessage(getString(R.string.logining));
	    getKaibesActivity().showProgressDialog();

	    // 避免界面卡顿
	    new Thread() {
		@Override
		public void run() {
		    String username = ((EditText) getView().findViewById(
			    R.id.etLoginUsername)).getText().toString().trim();
		    String passwrod = ((EditText) getView().findViewById(
			    R.id.etLoginPassword)).getText().toString().trim();

		    editor = getKaibesApplication().getAccountPreferences()
			    .edit();
		    editor.putString(StaticValuesUtil.USERNAME, username);

		    if (((CheckBox) getView().findViewById(R.id.cbLogin))
			    .isChecked()) {
			((CheckBox) getView().findViewById(R.id.cbPassword))
				.setChecked(true);
		    }

		    if (((CheckBox) getView().findViewById(R.id.cbPassword))
			    .isChecked()) {
			editor.putString(StaticValuesUtil.PASSWORD, passwrod);
		    }
		    editor.putBoolean("cbPassword", ((CheckBox) getView()
			    .findViewById(R.id.cbPassword)).isChecked());
		    editor.putBoolean("cbLogin", ((CheckBox) getView()
			    .findViewById(R.id.cbLogin)).isChecked());
		    editor.commit();
		    editor = null;

		    getKaibesApplication().setUsername(username);
		    getKaibesApplication().setPassword(passwrod);

		    getKaibesApplication().sendData(1,
			    SocketWorker.ACTION_LOGIN, username, passwrod);
		    super.run();
		}
	    }.start();

	    break;
	}
	case R.id.btnRegister:
	    getKaibesActivity().changeFragment(RegisterFragment.class);
	    break;

	default:
	    break;
	}
    }

    private void setUsernameAndPassword(String username, String password) {
	getKaibesApplication().setUsername(username);
	getKaibesApplication().setPassword(password);

	CleanableEditeText editeText = (CleanableEditeText) getView()
		.findViewById(R.id.etLoginUsername);
	editeText.setCallback(new Callback() {

	    @Override
	    public void onTextChanged(CharSequence s, int start, int before,
		    int count) {
	    }

	    @Override
	    public void beforeTextChanged(CharSequence s, int start, int count,
		    int after) {
	    }

	    @Override
	    public void afterTextChanged(Editable s) {
		String username = s.toString().trim();
		String photoName = getKaibesApplication().getUserPreferences()
			.getString(username, "");
		changePhoto(photoName);
	    }
	});
	editeText.setText(username);

	((EditText) getView().findViewById(R.id.etLoginPassword))
		.setText(password);
    }

    private void setData(String username, String password) {
	if (!username.equals("")) {
	    setUsernameAndPassword(username, password);
	    String photoName = getKaibesApplication().getUserPreferences()
		    .getString(username, "");
	    changePhoto(photoName);
	}

	((CheckBox) getView().findViewById(R.id.cbPassword))
		.setChecked(getKaibesApplication().getAccountPreferences()
			.getBoolean("cbPassword", true));
	((CheckBox) getView().findViewById(R.id.cbLogin))
		.setChecked(getKaibesApplication().getAccountPreferences()
			.getBoolean("cbLogin", false));
    }

    @Override
    public boolean onBackPressed() {
	exitApp();
	return false;
    }

    @Override
    protected void reset() {
    }

    private void changePhoto(String photoName) {
	Bitmap photo = null;

	if (!photoName.equals("")
		&& !photoName.equals(StaticValuesUtil.PHOTO_DEAFULT)) {
	    getKaibesApplication().setUserPhotoPathAndNotCreate(photoName);
	    if (getKaibesApplication().getUserPhotoPath().exists()
		    && getKaibesApplication().getUserPhotoPath().length() > 0) {
		photo = BitmapFactory.decodeFile(getKaibesActivity()
			.getKaibesApplication().getUserPhotoPath().toString());
	    }
	}

	if (photo != null) {
	    ((RoundImageView) getView().findViewById(R.id.ivPhotoLogin))
		    .setImageBitmap(photo);
	} else {
	    ((RoundImageView) getView().findViewById(R.id.ivPhotoLogin))
		    .setImageResource(R.drawable.photo_default);
	}
    }

    // ---------------------------GET AND SET 1--------------------------

    public void setUsername(String username) {
	this.username = username;
    }

    public void setPassword(String password) {
	this.password = password;
    }

}
